var TriggerBase = {};
TriggerBase.disableall = function(flag) {
    Ext.ComponentQuery.query("[name='triggerName']")[0].setDisabled(flag);
    Ext.ComponentQuery.query("[name='actionTiming']")[0].setDisabled(flag);
    Ext.ComponentQuery.query("[name='eventObjectTable']")[0].setDisabled(flag);
    Ext.ComponentQuery.query("[name='eventManipulation']")[0].setDisabled(flag);
    Ext.ComponentQuery.query("[name='actionStatement']")[0].setDisabled(flag);
};

TriggerBase.createSaveBtn = function(action) {
    var savebtn = Ext.create('Ext.Button', {
        text: '保存',
        itemId: 'savebtn',
        xtype: 'button',
        handler: function(mbtn) {
            TriggerBase.saveTrigger(action);
        }
    });
    return savebtn;
};

TriggerBase.createCancelBtn = function() {
    /*var cancelbtn = Ext.create('Ext.Button', {
		text: '取消',
		itemId: 'cancelbtn',
		xtype: 'button', 
		handler: function(cbtn){
			
			if(initaction === 'view'){
				TriggerBase.resetall('view');	
			}
			else{
				var theframe = window.parent.Ext.getCmp(tabId);
				theframe.destroy();
			}
			
		}
	}); */

    //return cancelbtn;
};

TriggerBase.createEditBtn = function() {
    return Ext.create('Ext.Button', {
        text: '编辑',
        itemId: 'editbtn',
        handler: function(btn) {
            TriggerBase.disableall(false);
            var savebtn = TriggerBase.createSaveBtn('edit');
            btn.ownerCt.add(savebtn);
            var cancelbtn = TriggerBase.createCancelBtn();
            btn.ownerCt.add(cancelbtn);
            btn.destroy();
        }
    });
};

TriggerBase.resetall = function(action) {

    var toolbarbtns = TriggerBase.createToolBar(action);

    var toolbar = Ext.ComponentQuery.query("[name='triggerMainPanel']")[0].getDockedItems('toolbar[dock="bottom"]')[0];

    toolbar.removeAll();

    for (var i = 0; i < toolbarbtns.length; ++i) {
        toolbar.add(toolbarbtns[i]);
    }

    if ((action === 'view' || action === 'edit') && triggerItem) {

        Ext.ComponentQuery.query("[name='triggerSchema']")[0].setValue(triggerItem.triggerSchema);
        Ext.ComponentQuery.query("[name='oldtriggerName']")[0].setValue(triggerItem.triggerName);

        Ext.ComponentQuery.query("[name='triggerName']")[0].setValue(triggerItem.triggerName);
        Ext.ComponentQuery.query("[name='actionTiming']")[0].setValue(triggerItem.actionTiming);
        Ext.ComponentQuery.query("[name='eventObjectTable']")[0].setValue(triggerItem.eventObjectTable);
        Ext.ComponentQuery.query("[name='eventManipulation']")[0].setValue(triggerItem.eventManipulation);

        if (triggerItem.actionStatement) {
            Ext.ComponentQuery.query("[name='actionStatement']")[0].setValue(triggerItem.actionStatement);
        }

        if (action === 'view') {
            TriggerBase.disableall(true);
        } else {
            TriggerBase.disableall(false);
        }

    } else if (action === 'create') {
        Ext.ComponentQuery.query("[name='triggerSchema']")[0].setValue(triggerItem.triggerSchema);
        TriggerBase.disableall(false);
    }

};

TriggerBase.saveModifiedTrigger = function(action) {
    var fieldvalues = TriggerBase.myformpanel.getForm().getFieldValues();
    	fieldvalues.actionStatement = Ext.ComponentQuery.query("[name='actionStatement']")[0].getValue();
        fieldvalues.dbName = nowDBName;
        fieldvalues.databaseId = dataBase_id;
        fieldvalues.datasourceId = dataSource_id;
        fieldvalues.dataSource = data_source;
        fieldvalues.baseType = now_db_type;
        fieldvalues.isLocal = isLocal;
        fieldvalues.sqlType = 'A SQL';
    var dorealmodifysave = function() {
        ajax({
            url: getRoot() + '/dataManage/executeScript',
            params: fieldvalues,
            method: 'POST',
            success: function(response) {
                var json = jsonDecode(response.responseText);
                if (json.success) {
                    $.message.success('Trigger ' + fieldvalues.triggerName + ' 修改成功.');
                    var theparent = window.parent;
                    theparent.object_panel.refreshone(theparent.objectTypeMap.progobjs);
                    triggerItem = json.root;
                    theparent.Ext.getCmp(tabId).setTitle('触发器: ' + fieldvalues.triggerName);
                    initaction = 'edit';
                    TriggerBase.resetall('edit');
                } else {
                    IDBUtil.showErrorMsgBox('Status', 'Trigger ' + fieldvalues.triggerName + ' 修改失败.', [json.root]);
                }
            },
            failure: function(result) {
                $.message.error('网络异常; 请尝试刷新页面。');
            }
        });
    };

    var premodifycheck = function() {
        ajax({
            url: getRoot()+'/trigger/getModifyTriggerSqlList',
            params: fieldvalues,
            method: 'POST',
            success: function(response) {
                var json = jsonDecode(response.responseText);
                if (json.success) {
                    var resultArray = json.root;
                    var allsqlstr = "";
                    for (var i = 0; i < resultArray.length; ++i) {
                        allsqlstr += resultArray[i] + "; \n";
                    }
                    var confirmButton = new Ext.Button({
                        text: '确定',
                        handler: function() {
                        	dorealmodifysave();

                            win.close();
                        }
                    });
                    var closeButton = new Ext.Button({
                        text: '关闭',
                        handler: function() {
                            win.close();
                        }
                    });
                    var sqlArea = new Ext.ux.form.field.CodeMirror({
                        readOnly: true,
                        value: allsqlstr,
                        autoScroll: true
                    });
                    var win = new IDB.Window({
                        title: ('确认执行如下SQL'),
                        width: 700,
                        height: 450,
                        closable: true,
                        layout: 'fit',
                        maximizable: true,
                        items: [sqlArea],
                        buttons: [confirmButton, closeButton]
                    });
                } else {
                    $.feedbackMessage({
                        type: 'warning',
                        message: json.errorCode
                    });
                }
            },
            failure: function(result) {
                $.message.error('网络异常; 请尝试刷新页面。');
            }
        });
    };
    var msg = TriggerBase.validateTrigger();
    if (msg) {
        $.message.warning(msg);
    } else { // precheck
    	premodifycheck();
    }
};

TriggerBase.validateTrigger = function() {

    var msglist = [];

    var triggerName = Ext.ComponentQuery.query("[name='triggerName']")[0].getValue();
    if (IDBUtil.isEmptyString(triggerName)) {

        msglist.push("触发器名称不能为空");
    }

    var actionTiming = Ext.ComponentQuery.query("[name='actionTiming']")[0].getValue();
    if (IDBUtil.isEmptyString(actionTiming)) {
        msglist.push("事件时间不能为空");
    }

    var eventObjectTable = Ext.ComponentQuery.query("[name='eventObjectTable']")[0].getValue();
    if (IDBUtil.isEmptyString(eventObjectTable)) {
        msglist.push("触发表不能为空");
    }

    var eventManipulation = Ext.ComponentQuery.query("[name='eventManipulation']")[0].getValue();
    if (IDBUtil.isEmptyString(eventManipulation)) {
        msglist.push("事件不能为空");
    }

    var actionStatement = Ext.ComponentQuery.query("[name='actionStatement']")[0].getValue();
    if (IDBUtil.isEmptyString(actionStatement)) {
        msglist.push("触发器语句不能为空");
    }

    var msg = "";

    if (msglist.length > 0) {

        msg = "<ul>";

        for (var i = 0; i < msglist.length; ++i) {
            msg += "<li>" + msglist[i] + "</li>";
        }

        msg += "</ul>";
    }

    return msg;

};

TriggerBase.saveAddTrigger = function() {

    var fieldvalues = TriggerBase.myformpanel.getForm().getFieldValues();
    	fieldvalues.actionStatement = Ext.ComponentQuery.query("[name='actionStatement']")[0].getValue();
        fieldvalues.dbName = nowDBName;
        fieldvalues.databaseId = dataBase_id;
        fieldvalues.datasourceId = dataSource_id;
        fieldvalues.dataSource = data_source;
        fieldvalues.baseType = now_db_type;
        fieldvalues.isLocal = isLocal;
        fieldvalues.sqlType = 'A SQL';
    var dorealsave = function(script) {
    	fieldvalues.script = script;
        ajax({
            url: getRoot() + '/dataManage/executeScript',
            params: fieldvalues,
            method: 'POST',
            success: function(response) {
                var json = jsonDecode(response.responseText);
                if (json.success) {
                    if (isLocal == 'isLocal') {
                        $.message.success("" + json.root + ' 创建触发器成功.');
                    } else {
                        $.feedbackMessage({
                            type: 'success',
                            message: json.root,
                            showTime: 5000
                        });
                    }
                    var theparent = window.parent;
                    theparent.object_panel.refreshone(theparent.objectTypeMap.progobjs);
                    theparent.Ext.getCmp(tabId).setTitle('触发器: ' + fieldvalues.triggerName);
                    initaction = 'edit';
                    TriggerBase.resetall('edit');
                    var newtabId = TabUtil.calculateExistingObjPreId(fieldvalues.triggerSchema, fieldvalues.triggerName, 'trigger');
                    window.parent.console_panel.saveOldNewPanelIdMap(tabId, newtabId);
                } else {
                    var trgname = Ext.ComponentQuery.query("[name='triggerName']")[0].getValue();
                    IDBUtil.showErrorMsgBox('Status', 'Trigger ' + trgname + ' 添加失败.', [json.root]);
                }
            },
            failure: function(result) {
                $.message.error('网络异常; 请尝试刷新页面。');
            }

        });
    };

    var precheck = function() {
        ajax({
            url: getRoot() + '/dataManage/trigger/getAddTriggerSaveSql',
            params: fieldvalues,
            method: 'POST',
            success: function(response) {
                var json = jsonDecode(response.responseText);
                if (json.success) {
                    var resultArray = json.root;
                    var allsqlstr = "DELIMITER $ \r\n";
                    for (var i = 0; i < resultArray.length; ++i) {
                        allsqlstr += resultArray[i];
                    }
                    allsqlstr += '$ \r\nDELIMITER ; \n';
                    var confirmButton = new Ext.Button({
                        text: '确定',
                        handler: function() {
                            dorealsave(sqlArea.value);

                            win.close();
                        }
                    });

                    var closeButton = new Ext.Button({
                        text: '关闭',
                        handler: function() {
                            win.close();
                        }
                    });
                    var sqlArea = new Ext.ux.form.field.CodeMirror({
                        readOnly: true,
                        value: allsqlstr,
                        autoScroll: true
                    });
                    var win = new IDB.Window({
                        title: ('确认执行如下SQL'),
                        width: 700,
                        height: 450,
                        closable: true,
                        layout: 'fit',
                        maximizable: true,
                        items: [sqlArea],
                        buttons: [confirmButton, closeButton]
                    });
                } else {
                    $.feedbackMessage({
                        type: 'warning',
                        message: json.errorCode
                    });
                }
            },
            failure: function(result) {
                $.message.error('网络异常; 请尝试刷新页面； ');
            }

        });
    };

    var msg = TriggerBase.validateTrigger();
    if (msg) {
        $.message.warning(msg);
    } else { // precheck
        precheck();
    }
};

TriggerBase.saveTrigger = function(action) {
    if (TriggerBase.myformpanel) {
//        if ('edit' === action) {
//            TriggerBase.saveModifiedTrigger();
//        } else if ('create' === action) {
//            TriggerBase.saveAddTrigger();
//        }
    	TriggerBase.saveAddTrigger();

    } // end of if

}; // end of savetrigger
TriggerBase.createDropTriggerBtn = function() {
	var script = 'drop trigger '+triggerItem.triggerName;
    var dropTrgBtn = {
        xtype: 'button',
        text: '删除trigger',
        handler: function(btn) {
            Ext.MessageBox.confirm('确认', '确认删除该触发器:' + triggerItem.triggerName,
            function(btn) {
                if (btn == 'yes') {
                    ajax({
                        url: getRoot()+'/dataManage/executeScript',
                        method: 'POST',
                        params: {
                            nowDBName: triggerItem.triggerSchema,
                            objectName: triggerItem.triggerName
                        },
                        success: function(response) {
                            var json = jsonDecode(response.responseText);
                            if (json.success) {
                                $.message.success('Trigger ' + triggerItem.triggerName + ' 删除成功.');
                                setTimeout(function() {
                                    var theparent = window.parent;
                                    theparent.object_panel.refreshone(theparent.objectTypeMap.progobjs);
                                    var theframe = theparent.Ext.getCmp(tabId);
                                    theframe.destroy();
                                },
                                1000);
                            }
                        },

                        failure: function(result) {
                            $.message.error('网络异常; 请尝试刷新页面； ');
                        }

                    });
                }
            });
        }
    };
    return dropTrgBtn;
};

TriggerBase.createToolBar = function(action) {
    if (action === 'view') {
        return [TriggerBase.createDropTriggerBtn(), TriggerBase.createEditBtn()];
    } else if ((action === 'create') || (action === 'edit')) {
        return [TriggerBase.createSaveBtn(action)];
    }
};
TriggerBase.createBasicForm = function(action) {
    var projectStore = new Ext.data.Store({
        fields: ['data', 'label'],
        data: projectListArray
    });
    var triggerTableStore = new Ext.data.Store({
        fields: ['text'],
        data: triggerItem.helperDo.allTableNames
    });
    var triggerTypeStore,triggerOptionStore;
    if(now_db_type == 'oracle'){
    	triggerTypeStore = ['BEFORE STATEMENT','BEFORE EACH ROW','AFTER STATEMENT','AFTER EACH ROW','INSTEAD OF','COMPOUND'];
    	triggerOptionStore = ['INSERT','DELETE','UPDATE','INSERT OR UPDATE','INSERT OR DELETE','UPDATE OR DELETE','INSERT OR UPDATE OR DELETE']
    }else{
    	triggerTypeStore = ['BEFORE','AFTER'];
    	triggerOptionStore = ['INSERT', 'UPDATE', 'DELETE'];
    }
    
    TriggerBase.myformpanel = Ext.create('Ext.form.Panel', {
        title: 'Trigger详情',
        name: 'triggerform',
        bodyPadding: 10,
        layout: 'column',
        region: 'north',
        buttonAlign: 'center',
        defaultType: 'textfield',
        defaults: {
            style: 'margin: 5px 70px 0px 15px; ',
            width: 300
        },
        items: [{
            xtype: 'hiddenfield',
            columnWidth: 0,
            name: 'oldtriggerName'
        },
        {
            xtype: 'hiddenfield',
            columnWidth: 0,
            name: 'triggerSchema'
        },
        {
            columnWidth: 0.5,
            fieldLabel: '<span style="color:red">*</span>邮箱',
            emptyText: '请输入部门负责人邮箱地址',
            allowBlank: false,
            name: 'auserEmail',
            blankText: '部门负责人邮箱地址不能为空'
        },
        {
            columnWidth: 0.5,
            fieldLabel: '项目组',
            xtype: 'combo',
            triggerAction: 'all',
            displayField: 'label',
            valueField: 'data',
            queryMode: 'local',
            name: 'projectName',
            forceSelection: true,
            typeAhead: true,
            editable: false,
            store: projectStore
        },
        {
            labelStyle: 'width: 120px',
            columnWidth: 0.5,
            fieldLabel: '<span style="color:red">*</span> SQL用途',
            allowBlank: false,
            name: 'sqlUsage',
            blankText: 'SQL用途说明不能为空.'
        },
        {
            fieldLabel: "触发器名称(*)",
            labelStyle: 'width: 120px',
            disabled: true,
            columnWidth: 0.5,
            name: 'triggerName',
            id: 'triggger_name_field'
        },
        {
            xtype: 'combobox',
            name: 'eventObjectTable',
            columnWidth: 0.5,
            labelStyle: 'width: 120px',
            displayField: 'text',
            valueField: 'text',
            queryMode: 'local',
            forceSelection: true,
            store: triggerTableStore,
            fieldLabel: "触发表(*)",
            editable: false,
            disabled: true

        },
        {
            xtype: 'combobox',
            fieldLabel: "事件时间(*)",
            name: 'actionTiming',
            labelStyle: 'width: 120px',
            store: triggerTypeStore,
            columnWidth: 0.5,
            editable: false,
            disabled: true
        },
        {
            xtype: 'combobox',
            name: 'eventManipulation',
            fieldLabel: "事件(*)",
            columnWidth: 0.5,
            labelStyle: 'width: 120px',
            store: triggerOptionStore,
            forceSelection: true,
            editable: false,
            disabled: true
        }],
        renderTo: Ext.getBody()
    });
    return TriggerBase.myformpanel;
};

TriggerBase.createTriggerBodyPart = function() {
    var sqlArea = new Ext.ux.form.field.CodeMirror({
        name: 'actionStatement',
        id: 'sql_area_content',
        autoScroll: true,
        value: 'begin\n\n/**trigger body**/\n\nend'
    });
    var sqlpanel = new Ext.Panel({
        region: 'center',
        flex: 65 / 100,
        title: '触发器语句(*)',
        layout: 'fit',
        items: [sqlArea],
        border: false
    });
    return sqlpanel;
};

TriggerBase.createTriggerForm = function() {

    var list = [];

    list[0] = TriggerBase.createBasicForm();
    list[1] = TriggerBase.createTriggerBodyPart();

    TriggerBase.allpanels = Ext.create('Ext.panel.Panel', {
        layout: 'border',
        name: 'triggerMainPanel',
        border: false,
        buttons: TriggerBase.createToolBar(initaction),
        buttonAlign: 'center',
        items: list
    });
};

Ext.onReady(function() {
    TriggerBase.createTriggerForm(initaction);

    var formwrapper = Ext.create('Ext.Viewport', {
        layout: 'fit',
        items: [TriggerBase.allpanels],
        renderTo: Ext.getBody()
    });

    if (initaction == 'view') {
        TriggerBase.resetall(initaction);
        TriggerBase.disableall(true);
    } else if ((initaction == 'create') || (initaction == 'edit')) {
        TriggerBase.resetall(initaction);
        TriggerBase.disableall(false);

    }

});